var Relational = function() {
    this.url = null;
    this.timer = null;
    this.condition = null;
    this.item = null;
    this.export_url = "";
    this.con = {};
    this.current_request = null;
    this.oDiv = null;

    this.x = 0;
    this.y = 0;
    this.context = null;

    this.target = null;
    this.dataBase = {};

    this.xhead = null;
    this.yhead = null;


};

Relational.prototype = {


    init: function(url, condition,  item ,self)
    {

        this.condition = condition;

        this.context = self;

        this.url = url;

        this.export_url = url.substring(0,url.lastIndexOf("/")+1)+"export";
        
        this.item = item;

        this.addListener();


    },
    addListener: function() {

        var _this = this;

        $(window).click(function(ev) {

            _this.x = ev.clientX;

            _this.y = ev.clientY;

            var table = $(ev.target).closest("table");

            if(!table.attr("data-status")){
                return ;
            }

            var data_t = table.attr("data-type");

            clearTimeout( _this.timer );

            if ( ev.target.tagName == "TD") {

                _this.timer = setTimeout(function() {

                    try{
                        _this.xhead= ev.target._sibhead[0];
                        _this.yhead = ev.target._sibrows[0];

                    }catch (e){
                        _this.removeDiv( ev, _this.target );
                        return ;
                    }

                    if(!_this.yhead||!_this.xhead||!_this.xhead.getAttribute||!_this.yhead.getAttribute){
                        return ;
                    }

//                    var xName = _this.xhead.getAttribute("data-axis");
                    var xValue = _this.xhead.getAttribute("data-id");
//                    var yName = _this.yhead.getAttribute("data-axis");
                    var yValue = _this.yhead.getAttribute("data-id");
                    var item  = _this.item&&_this.item.call(_this.context);

                    if(item){
                        var xA =  item["d"]["h"]["a"].join(",");
                        var yA =  item["d"]["r"]["a"].join(",");

                    }else{
                        return;
                    }

                    _this.xId = xValue;
                    _this.yId = yValue;

                    //获取条件
                    var  condition = _this.condition.call( _this.context );

                    _this.con = {};

                    if(condition["where"]){
                        for(var i in condition["where"]){

                            if(condition["where"][i].length != 0){
                                _this.con[i] = condition["where"][i];
                            }

                        }
                    }else{
                        for(var i in condition){

                            if(condition[i].length != 0) {
                                _this.con[i] = condition[i];
                            }
                        }
                    }

                    _this.con[ xA ] = xValue;
                    _this.con[ yA ] = yValue;

                    _this.con["t"] = data_t;

                    _this.createNotice( _this.x + 5 , _this.y );

                    var dt = _this.dataBase[ JSON.stringify( _this.con ) ];

                    if( dt ){
                        _this.success.call( _this, dt );
                    }else{
                        if (_this.current_request) { _this.current_request.abort();}
                        //ajax请求
                        _this.current_request = $.ajax({context: _this, url: _this.url, data: _this.con, type: "post",async : false, success: _this.success });
                    }

                    _this.target = ev.target;

                }, 100);
            }
        });


        $(window).mousedown(function( ev ){

            if(ev.which == 3){

                _this.removeDiv();
                ev.stopPropagation();
                ev.preventDefault();

                return false;
            }else if( ev.which == 1&&$(ev.target).parents("#big-data-id").length != 1 ){

                _this.removeDiv();
            }

        });

        $("#ad-js-tableResponsive,#ad-js-tablecontainer").scroll(function(){
           _this.removeDiv();
        });

        $( window ).resize(function(){
            _this.removeDiv();
        });


    },
    removeDiv: function(ev) {

        if (this.current_request) { this.current_request.abort();}

        var div = document.getElementById("big-data-id");

        if(!div)
        {
            return;
        }

        if (ev&&ev.target != this.target && ev.target != div ) {

            if (div && div.parentNode) {

                div.parentNode.removeChild(div);

                this.oDiv = null;

                this.target = null;
            };
        }

        if (!ev &&div && div.parentNode) {

            div.parentNode.removeChild(div);

            this.oDiv = null;

            this.target = null;
        };


    },
    success: function(data) {

        if(!this.oDiv||data.status ==0){
            this.removeDiv();
            this.context.toastr.warning("此表不支持数据挖掘！");
            return false;
        }

        var _this = this;
        $( _this.oDiv ).addClass("noImage");

        if( !data || ( data.length == 1|| data.length == 0 ) )
        {
            data = [["查无数据"]];
        }


        _this.dataBase[ JSON.stringify(_this.con) ] = data;

        //创建表格
        var tb = this.createTable( data );

        //创建标题
        var titleDiv = document.createElement("div");

        titleDiv.className = "big-data-title";

        var exportName = this.xhead.getAttribute("data-str").replace("&lt;","<").replace("&gt;",">")
            +"与"+this.yhead.getAttribute("data-str").replace("&lt;","<").replace("&gt;",">")+"数据挖掘表";

         var html =  "<span style='float: left;'><i class='fa fa-flash'></i> 当前条件：</span>" +
             "<span style='text-decoration:underline;float:left;font-size: inherit;'>"+ this.xhead.getAttribute("data-str")  +"</span>" +
             "<span style='float: left;margin:0 5px;'>与</span>" +
             "<span style='text-decoration:underline;float:left; font-size: inherit;'>"+  this.yhead.getAttribute("data-str") +"</span>" +
             "<a style='color: #fff; float: right; cursor: pointer;margin-left: 20px;'><i class='fa fa-times'></i></a>";

         if( data &&data.length!=0&&data.length!=1){
             html+="<a id='down_data' style='color: #fff; float: right; cursor: pointer;margin-left: 20px;' href='javascript:void(0);'><i class='fa fa-download'></i></a>";
         }
        titleDiv.innerHTML = html ;

        var json = { "data": data, "name": exportName };

        $("body").on( "click" , "#down_data" ,function(){
            var str = encodeURIComponent( JSON.stringify( json ) );
            _this.down(_this.export_url, str );
        });


        titleDiv.getElementsByTagName("a")[ 0 ].onclick = function()
        {
            _this.removeDiv();
        };

        this.oDiv.innerHTML = "";

        this.oDiv.appendChild( titleDiv );

        this.oDiv.appendChild( tb );

        //调整位置
        this.changeLocation();

    },

    down:function( url , val ){

        var sForm = document.getElementById("down-form");
        if(sForm)document.body.removeChild( sForm );
        var oForm = document.createElement("form");
        oForm.style["display"] = "none";
        oForm.setAttribute("action",url);
        oForm.setAttribute("method","post");
        oForm.setAttribute("id","down-form");
        var oInput = document.createElement("input");
        oInput.setAttribute("name","data");
        oInput.setAttribute("value",val);
        oForm.appendChild( oInput );
        document.body.appendChild( oForm );
        oForm.submit();
    },

    changeLocation: function() {

        this.oDiv.style["top"] = 0 ;
        this.oDiv.style["left"] = 0 ;

        if((this.x + this.oDiv.offsetWidth) >= document.body.offsetWidth -10 ){

            this.oDiv.style["left"] = (this.x - this.oDiv.offsetWidth)>0 ? (this.x- this.oDiv.offsetWidth)+ "px":0;
        }else{

            this.oDiv.style["left"] = this.x +10 +"px";
        }

        if((this.y + this.oDiv.offsetHeight) >= document.body.offsetHeight -10){

            this.oDiv.style["top"] = (this.y- this.oDiv.offsetHeight)>0 ? (this.y- this.oDiv.offsetHeight)+ "px":0 ;
        }else{
            this.oDiv.style["top"] = this.y +"px";
        }

    },

    createNotice: function(x, y) {

        var nt = document.getElementById("big-data-id") || document.createElement("div");


        //调整加载位置
        if(this.y >= document.body.offsetHeight-100){
            y -= 80;
        }
        if(this.x >= document.body.offsetWidth-100){
            x -= 80;
        }

        nt.style["left"]     = x + "px";
        nt.style["top"]      = y + "px";
        nt.className = "big-data-show-box";
        nt.id = "big-data-id";

        this.oDiv = nt;

        nt.innerHTML = "<span style='margin-left: 20px; padding: 5px 10px; display: block;'>努力加载中</span>";

        document.body.appendChild(nt);
    },

    createTable: function(data)
    {
        var tb = document.createElement("table");
        var thead = document.createElement("thead");
        var tbody = document.createElement("tbody");

        tb.className = "table table-bordered table-striped table-hover";
        tb.style.color = "#333";

        for (var i = 0; i < data.length; i++) {

            var tr = document.createElement("tr");

            for (var j = 0; j < data[i].length; j++) {

                var td = document.createElement("td");

                if (i == 0)
                {
                    td = document.createElement("th");
                }

                td.innerHTML = data[i][j];

                tr.appendChild(td);
            }

            if( i == 0 )
            {
                thead.appendChild( tr );
            }
            else
            {
                tbody.appendChild( tr );
            }
        }

        tb.appendChild( thead );

        tb.appendChild( tbody );

        return tb;
    }

};

